package com.cheng.dreams.sample.presenter;

import android.content.Context;
import android.widget.Toast;

import com.cheng.dreams.sample.entity.response.BaseResponse;
import com.cheng.dreams.sample.net.ApiService;
import com.cheng.dreams.sample.net.NetClient;
import com.cheng.dreams.sample.util.NetUtil;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;


/**
 * Created by Snow on 2016/11/7.
 * Description:
 */

public class BasePresenter<T> {
    protected ApiService mService;
    protected Context mContext;
    private final long RETRY_TIMES = 1;
    protected ObservableTransformer<BaseResponse<T>, BaseResponse<T>> mObservableTransformer;

    public BasePresenter(Context context) {
        mContext = context;
        mService = NetClient.getInstance();
        init();
    }

    private void init() {
        mObservableTransformer = new ObservableTransformer<BaseResponse<T>, BaseResponse<T>>() {
            @Override
            public ObservableSource<BaseResponse<T>> apply(Observable<BaseResponse<T>> observable) {
                Observable<BaseResponse<T>> baseResponseObservable = observable.retry(RETRY_TIMES)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .unsubscribeOn(Schedulers.io())
                        .doOnSubscribe(new Consumer<Disposable>() {
                            @Override
                            public void accept(Disposable disposable) throws Exception {
                                if (!NetUtil.isConnected(mContext)) {
                                    disposable.dispose();
                                    Toast.makeText(mContext, "网络连接异常,请检查网络", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                return baseResponseObservable;
            }
        };

    }
}
